import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/login.vue'
import Test from '../views/test.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/Test',
    name: 'Test',
    component: Test
  },
  {
    path: '/',
    name: 'Login',
    component: Login
  },
  {
    path: '/Index',
    component: () => import('../views/index/index.vue'),
    children: [
      {
        path: '/Index',
        redirect: '/Index/fanInfo'
      },
      {
        path: '/Index/fanInfo',
        name: 'fanInfo',
        component: () => import('../views/index/fanInfo/fanInfo.vue')
      },
      {
        path: '/Index/module',
        name: 'module',
        component: () => import('../views/index/module/module.vue')
      },
      {
        path: '/Index/project',
        name: 'project',
        component: () => import('../views/index/project/project.vue')
      },
      {
        path: '/Index/cusManagement',
        name: 'cusManagement',
        component: () => import('../views/index/cusManagement/cusManagement.vue')
      },
      {
        path: '/Index/module/detail',
        name: 'moduleDetail',
        component: () => import('../views/index/module/components/moduleDetail.vue'),
        children: [
          {
            path: '/Index/module/detail/file',
            name: 'moduleDetailFile',
            component: () => import('../views/index/module/components/fileManage.vue')
          },
          {
            path: '/Index/module/detail/model',
            name: 'moduleDetailModel',
            component: () => import('../views/index/module/components/modelManage.vue')
          },
          {
            path: '/Index/module/detail/other',
            name: 'moduleDetailOther',
            component: () => import('../views/index/module/components/otherSourceManage.vue')
          },
          {
            path: '/Index/module/detail/result',
            name: 'moduleDetailResult',
            component: () => import('../views/index/module/components/result.vue')
          }
        ]
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由控制守卫
router.beforeEach((to, from, next) => {
  if (to.path === '/') return next()
  const tokenStr = JSON.parse(sessionStorage.getItem('data'))
  if (!tokenStr || tokenStr === '') {
    alert('请先登录!')
    return next('/')
  }
  next()
})

// 解决重复点击路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) {
    return originalPush.call(this, location, onResolve, onReject)
  }
  return originalPush.call(this, location).catch(err => err)
}

export default router
